<template>
  <view>
    <!--顶栏-->
    <view class="head">
      <view class="search-bar">
        <u-search @change="search()" @search="search()" @clear="keyword=''" v-model="keyword" shape="round" clearabled
                  :show-action="false" placeholder="请输入书名关键字"></u-search>
      </view>
      <view class="head-button">
        <u-button @click="addClick" :custom-style="{border:'none'}" :hairline="false" icon="plus-circle"
                  size="large"></u-button>
        <u-action-sheet
            title="添加图书"
            cancel-text="取消"
            :actions="addActionList"
            :show="addStatus"
            @close="this.addStatus=false"
            @select="addActionClick"
        ></u-action-sheet>
      </view>
      <view class="head-button">
        <u-button @click="moreClick" :custom-style="{border:'none'}" :hairline="false" icon="list"
                  size="large">
          <!--选择标签-->
          <view class="tag-popup">
            <u-popup
                :show="moreStatus"
                mode="right"
                @close="this.moreStatus=false"
                overlay-opacity="0"
                :custom-style="{padding:'15px',boxShadow: '0 3px 10px 0px rgba(0, 0, 0, 0.1)'}"
                :safeAreaInsetBottom="true">
              <!--标题-->
              <view class="title">
                <u-text
                    text="书籍标签"
                ></u-text>
              </view>
              <!--标签-->
              <scroll-view
                  class="tag"
                  scroll-y="true">
                <view
                    v-for="(item,index) in tagList"
                    :key="index"
                    class="tag-item">
                  <u-tag
                      @click="tagClick(index)"
                      :text="item.content"
                      :border-color="item.color"
                      :color="item.selected?'#ffffff':item.color"
                      :bg-color="!item.selected?'#ffffff':item.color"
                      shape="circle"
                      :plain="item.selected"
                  ></u-tag>
                </view>
              </scroll-view>
              <!--关闭-->
              <view class="btn-close">
                <u-button
                    text="关闭"
                    type="error"
                    plain
                    size="medium"
                    @click="this.moreStatus=false"
                ></u-button>
              </view>
            </u-popup>
          </view>
        </u-button>
      </view>
    </view>
    <!--图书列表-->
    <view class="content">
      <u-cell-group
          :border="false">
        <view
            class="item"
            v-for="(item,index) in bookListFilter"
            :key="index"
            v-if="!loadingStatus">
          <u-cell
              :is-link="true"
              @click="navigate2BookEdit(item)">
            <!--封面-->
            <view
                slot="icon"
                class="cover">
              <u-image
                  :src="item.cover"
                  mode="aspectFill"
                  width="10vw"
                  height="14.9vw"
              ></u-image>
            </view>
            <!--书名-->
            <view
                slot="title"
                class="title">
              <u-text
                  :text="item.name"
                  :lines="1"
              ></u-text>
            </view>
            <!--详细信息-->
            <view
                slot="label"
                class="text">
              <u-text
                  :text="item.author"
                  type="primary"
                  size="12"
              ></u-text>
              <u-text
                  :text="item.pubHouse"
                  type="info"
                  size="12"></u-text>
            </view>
          </u-cell>
        </view>
        <view
            v-for="item in loadingCardList"
            v-if="loadingStatus">
          <view class="loading">
            <u-skeleton
                rows="2"
                :avatar="true"
                :title="false"
                avatar-size="10vw"
                avatar-shape="square"
            ></u-skeleton>
          </view>
        </view>
      </u-cell-group>
      <view class="divider">
        <u-divider :text="`共${listLength}本书`"></u-divider>
      </view>
    </view>


  </view>
</template>

<script>
export default {
  data() {
    return {
      bcList: [],
      tagList: [],
      bookIds: [],
      loadingCardList: [1, 2, 3, 4, 5, 6, 7, 8, 9],
      addActionList: [
        {
          name: '扫码添加',
          param:'scan'
        },
        {
          name: '手动添加'
        }
      ],
      keyword: '',
      listLength: 0,
      moreStatus: false,
      addStatus: false,
      loadingStatus: true,
      tagSelectStatus: false
    }
  },
  methods: {
    //搜索过滤
    search(value) {
      this.keyword = value
    },
    //获取信息
    async getInfo() {
      this.loadingStatus = true
      try {
        const db = uniCloud.database();
        const dbCmd = db.command
        const $ = db.command.aggregate
        let bookRes = (await db.collection('book')
            .field("_id,cover,name,status,author,pubHouse")
            .get()).result.data
        let tagsRes = (await db.collection('label')
            .aggregate()
            .match({
              enableFlag: dbCmd.eq(true)
            })
            .lookup({
              from: 'inner_label_book',
              let: {
                lId: '$_id'
              },
              pipeline: $.pipeline()
                  .match(dbCmd.expr($.eq(['$labelId', '$$lId'])))
                  .project({
                    bookId: 1
                  })
                  .done(),
              as: 'bookIds'
            })
            .project({
              content: 1,
              color: 1,
              bookIds: 1
            })
            .end()).result.data
        this.bcList = bookRes
        tagsRes.forEach((value, index, array) => {
          value.selected = false
        })
        this.tagList = tagsRes
      } catch (e) {
        console.log(e)
      } finally {
        this.loadingStatus = false
        uni.stopPullDownRefresh()
      }
    },
    //卡片点击跳转
    cardClick(colum) {
      uni.navigateTo({url: '/pages/BookDetail?_id=' + colum._id})
    },
    moreClick() {
      this.moreStatus = true
    },
    addClick() {
      this.addStatus = true
    },
    addActionClick(value) {
      switch (value.name) {
        case '扫码添加':{
          uni.navigateTo({
            url:'/pages/BookAddOrUpdate?scan='+true
          })
        }break;
        case '手动添加':{
          uni.navigateTo({
            url:'/pages/BookAddOrUpdate'
          })
        }break;
        default:{
          console.log("非法action",value.name)
        }break;
      }

    },
    //标签点击
    tagClick(ind) {
      this.tagList.forEach((value, index, array) => {
        if (ind === index) {
          value.selected = !value.selected
          this.bookIds = value.selected ? value.bookIds : []
          this.tagSelectStatus = value.selected

        } else {
          value.selected = false
        }
      })
    },
    navigate2BookEdit(item) {
      uni.navigateTo({
        url: '/pages/BookAddOrUpdate?bookId=' + item._id,
        animationType: 'pop-in'
      })
    }
  },
  computed: {
    bookListFilter() {
       let list = this.bcList.filter(data => {
        let keyCon = true
        let tagCon = true
        //检查搜索关键词
        if (this.keyword !== '') {
          keyCon = (data.name.indexOf(this.keyword, 0) !== -1) || (data.author.indexOf(this.keyword, 0) !== -1)
        }
        //检查是否分类选择
        if(this.bookIds.length !== 0 || this.tagSelectStatus ){
          tagCon = this.bookIds.some(value => {
            if (this.tagSelectStatus) {
              return (value.bookId === data._id)
            }
            return true
          })
        }
        return tagCon && keyCon
      })
      this.listLength = list.length
      return list
    }
  },
  onLoad() {
    this.getInfo()
  },
  onPullDownRefresh() {
    this.getInfo()
  }
}
</script>

<style lang="scss" scoped>
.tag-popup {
  .title {
    margin-bottom: 10px;
  }

  .tag {
    min-height: 85vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .tag-item {
      display: flex;
      margin-top: 10px;
      margin-bottom: 10px;
    }
  }

  .btn-close {
    padding-top: 10px;
    padding-bottom: 10px;
  }
}

.content {
  margin-top: 10px;

  .divider {
    margin: 0 15px;
  }

  .item {
    .title{
      margin-left: 10px;
    }
    .text {
      margin-left: 10px;
      margin-top: 2px;
    }
  }
  .loading{
    margin: 10px 15px;
  }
}

.head {
  margin: 0 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-items: center;

  .search-bar {
    width: 100%;
  }

  .head-button {
    width: 10vw;
  }
}

</style>
